package com.xiaoyin.community.Service;

import com.xiaoyin.community.Domain.SolrDataDomain;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yinjianping@baidu.com on 2018/7/24.
 *
 * @Description:
 * @Modified By:
 */
@Service
public class SolrService {

    private final static String candicate_id = "candicate_id";
    private final static String candicate_name = "candicate_name";
    private final static String candicate_class = "candicate_class";
    private final static String candicate_phone = "cnadicate_phone";

    @Resource
    private SolrClient solrClient;

    public List<SolrInputDocument> testAdd(List<SolrDataDomain> listData)throws IOException,SolrServerException{
        List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
        for (SolrDataDomain data:listData
             ) {
            SolrInputDocument doc = new SolrInputDocument();
            doc.setField(candicate_id,data.getCandicate_id().toString());
            doc.setField(candicate_name,data.getCandicate_name());
            doc.setField(candicate_class,data.getCandicate_class());
            doc.setField(candicate_phone,data.getCandicate_phone());

            docs.add(doc);

            solrClient.add(docs);
            solrClient.commit();
        }
        return docs;
    }

    public SolrDocumentList query(String word,Integer page,Integer rows)throws IOException,SolrServerException{
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.set("q","candicate_name:"+word);
        solrQuery.setStart((Math.max(page,1)-1)*rows);
        solrQuery.setRows(rows);
        solrQuery.addHighlightField("candicate_name,candicate_class");
        QueryResponse queryResponse = solrClient.query(solrQuery);

        SolrDocumentList docs = queryResponse.getResults();

        return docs;
    }

}
